import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  Button,
  Tag,
  Modal,
  Form,
  message,
  Table,
  Radio,
  Input,
  Icon,
  Drawer,
  Row,
  Col,
  Switch,
  Progress, DatePicker, TreeSelect, Select, Tooltip,
} from 'antd';
import MyPagination from '@/components/MyPagination';
import Loading from '@/components/Loading';

import find from 'lodash/find';
import { getTimeDistance, renderValveOpen, download, formateObjToParamStr, renderTreeNodes } from '@/utils/utils';

import debounce from 'lodash/debounce';
import { routerRedux } from 'dva/router';
import BuildModalTitle from '@/components/BuildModalTitle';
import ReactDataGrid from 'react-data-grid';
import ReactEcharts from 'echarts-for-react';
import forEach from 'lodash/forEach';
import merge from 'lodash/merge';
import get from 'lodash/get';
import map from 'lodash/map';
import config from '../../config/config';
import request from '@/utils/request';
import Detail from '../Owner/Detail';

const FormItem = Form.Item;
const { confirm } = Modal;
const ButtonGroup = Button.Group;
const RadioButton = Radio.Button;

const RadioGroup = Radio.Group;

@connect(({ old_meter_logs, loading, global }) => ({
  old_meter_logs,
  global,
  loading: loading.models.old_meter_logs,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      selectedRowKeys: [],
      btnLoading: false,
      data: [],
    };
  }


  componentDidMount() {

    const { dispatch } = this.props;
    const {
      old_meter_logs: { pageLoaded, scrollData },
    } = this.props;
    console.log('pageLoaded', pageLoaded);
    const table = document.querySelector('.react-grid-Canvas');
    if (pageLoaded) {
      setTimeout(() => {
        table.scrollTop = scrollData.y;
        table.scrollLeft = scrollData.x;
      }, 0);

    } else {
      const {
        old_meter_logs: { searchParams },
      } = this.props;
      console.log('searchParams', searchParams);
      dispatch({
        type: 'old_meter_logs/fetch',
        payload: searchParams,
        callback: () => {
          const { dispatch } = this.props;
          dispatch({
            type: 'old_meter_logs/changeLoaded',
          });
          dispatch({
            type: 'old_meter_logs/changeTableY',
          });
        },
      });

    }
    window.addEventListener('resize', this.resize);
    table.addEventListener('scroll', debounce(this.scroll, 150));
    const that = this;
    request(`/all_regions`, {
      method: 'GET',
    }).then((response) => {
      if (response.status === 200) {
        that.setState({
          data: response.data.data,
        });
      }

    });
  }

  scroll = (e) => {
    console.log('scroll');
    const { dispatch } = this.props;
    dispatch({
      type: 'old_meter_logs/changeScroll',
      payload: {
        x: e.target.scrollLeft,
        y: e.target.scrollTop,
      },
    });
  };

  resize = () => {
    const { dispatch } = this.props;

    // this.changeTableY();
    dispatch({
      type: 'old_meter_logs/changeTableY',
    });
  };
  changeTableY = () => {
    this.setState({
      tableY: document.querySelector('.bottom-analysis').getBoundingClientRect().top -
        document.querySelector('.custom-small-table').getBoundingClientRect().top - 50,
    });
  };

  componentWillUnmount() {
    console.log('componentWillUnmount');
    window.removeEventListener('resize', this.resize);
    return;
    const table = document.querySelector('.ant-table-body');
    table.removeEventListener('scroll', debounce(this.scroll, 300));
  }

  handleSearch = (values, cb) => {
    console.log('handleSearch', values);
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'old_meter_logs/fetch',
      payload: {
        ...values,
      },
      callback() {
        console.log('handleSearch callback');
        if (cb) cb();
      },
    });
  };


  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
    this.handleSearch({
      region_id: '',
      region_name: '',
      name:'',
      mobile:'',
      meter_number:'',
      start_date: moment(getTimeDistance('year')[0]).format('YYYY-MM-DD'),
      end_date: moment().format('YYYY-MM-DD'),
    });
  };
  keyPress=(e)=>{
    let theEvent = e || window.event;
    let code = theEvent.keyCode || theEvent.which || theEvent.charCode;
    if (code === 13) {
      e.preventDefault();
      console.log('key press')
      const {
        old_meter_logs: { searchParams },
      } = this.props;
      const { form } = this.props;
      form.validateFields((err, fieldsValue) => {
        if (err) return;

        this.searchFunc()

      });
    }
  }
  searchFunc=()=>{
    const that=this
    const { form , old_meter_logs: { searchParams}} = that.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;

      that.handleSearch({
        page: 1,
        per_page: searchParams.per_page,
        ...fieldsValue,
        region_id:fieldsValue.region_id?fieldsValue.region_id.split('$')[0]:'',
        region_name:fieldsValue.region_id?fieldsValue.region_id.split('$')[1]:'',

      },function() {
        const {
          old_meter_logs: { scrollData },
        } = that.props;
        const table = document.querySelector('.react-grid-Canvas');
        if(table){
          setTimeout(() => {
            table.scrollTop = 0;
            table.scrollLeft = scrollData.x;
          }, 0);
        }
      });

    });
  }
  renderSimpleForm() {
    const data = this.state.data;
    const {
      form: { getFieldDecorator },
      old_meter_logs: { searchParams },
    } = this.props;
    const { form } = this.props;
    const that = this;
    return (
      <Form layout="inline" className="search-form">
        <FormItem label="区域">
          {getFieldDecorator('region_id', {
            initialValue: searchParams.region_id ? `${searchParams.region_id}$${searchParams.region_name}` : '',
          })(
            <TreeSelect
              style={{ width: '130px' }}
              allowClear
              treeDefaultExpandAll
              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
              showSearch
            >
              {renderTreeNodes(data)}
            </TreeSelect>,
          )}
        </FormItem>
        <FormItem label="户主姓名">
          {getFieldDecorator('name', {
            initialValue: searchParams.name,
          })(<Input style={{ width: '120px' }} placeholder="请输入"  onKeyPress={this.keyPress}/>)}
        </FormItem>
        <FormItem label="户主手机">
          {getFieldDecorator('mobile', {
            initialValue: searchParams.mobile,
          })(<Input style={{ width: '120px' }} placeholder="请输入"  onKeyPress={this.keyPress}/>)}
        </FormItem>
        <FormItem label="水表号">
          {getFieldDecorator('meter_number', {
            initialValue: searchParams.meter_number,
          })(<Input style={{ width: '150px' }} placeholder="请输入"  onKeyPress={this.keyPress}/>)}
        </FormItem>
        <FormItem>
          <Button
            type="primary"
            icon='search'
            onClick={() => {
              this.searchFunc()
            }}
          >
            查询
          </Button>
          <Button style={{ marginLeft: 8 }} icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>
          <Tooltip title={'导出前请查询一次 '}>
            <Button type={'primary'} className={'btn-cyan'}
                    style={{ marginLeft: 8 }} icon='export'
                    onClick={this.handleExport}>
              导出报表
            </Button>
          </Tooltip>
        </FormItem>

      </Form>
    );
  }

  isActive(type) {
    const {
      old_meter_logs: { searchParams },
    } = this.props;
    const value = getTimeDistance(type);
    if (!searchParams.start_date || !searchParams.end_date) {
      return false;
    }
    if (moment(searchParams.start_date).isSame(value[0], 'day') && moment(searchParams.end_date).isSame(value[1], 'day')) {
      return true;
    }
  }

  handleExport=()=>{
    const {
      old_meter_logs: { searchParams },
    } = this.props;
    const payload= {
      ...searchParams
    }
    download(`${config.prefix}/old_meter_log_files?Authorization=Bearer ${sessionStorage.getItem('token')}&${formateObjToParamStr(payload)}`)
  }
  render() {
    const that = this;
    const {
      old_meter_logs: { data, loading, tableY, meta, searchParams, selectedRowKeys, additional },
      global: { gridTableW },
    } = this.props;

    const defaultColumnProperties = {
      resizable: true,
    };
    const columns = [
      {
        name: '序号',
        width: 50,
        key: '_index',
        frozen: true,
        formatter: (event) => {
          return <p className={'index'}>{event.value + 1}</p>;
        },
      },
      {
        name: '户主姓名',
        frozen: true,
        width: 150,
        key: 'name',
      },
      {
        name: '户主地址',
        width: 200,
        key: 'address',
      },
      {
        name: '户主手机',
        width: 120,
        key: 'mobile',
      },
      {
        name: '新系统水表号',
        width: 150,
        key: 'new_meter_number',
        formatter: (event) => {
          return <span onClick={()=>{
            this.setState({
              editRecord: {
                ...event.row,
                meter_number:event.value,
                my_account_id:event.row.new_account_id
              },
              infoModal: true,
            });
          }} style={{color:'#0062dc',cursor:'pointer'}} title={event.value}>{event.value }</span>;
        },
      },
      {
        name: '旧系统水表号',
        width: 155,
        key: 'old_meter_number',
      },

    ].map(c => ({ ...defaultColumnProperties, ...c }));

    let totalWidth = 0;
    for (let i = 0; i < columns.length; i++) {
      totalWidth += columns[i].width;
    }
    if (totalWidth < gridTableW) {
      columns[columns.length - 1].width = columns[columns.length - 1].width + gridTableW - totalWidth;
    }
    return <div className="custom-card">
      <div className="table-title"><span className={'title-item'}>旧系统水表报表</span>
      </div>
      <div className="table-page">
        <div className="table-condition">{this.renderSimpleForm()}</div>
        <div className={'table-data-content'}>
          <ReactDataGrid
            columns={columns}
            rowGetter={i => {
              return { ...data[i], _index: i };
            }}
            rowsCount={data.length}
            minHeight={tableY}
            rowSelection={{
              showCheckbox: false,
              enableShiftSelect: true,
              selectBy: {
                indexes: selectedRowKeys,
              },
            }}
            onRowClick={
              (row) => {
                if (!String(row)) {
                  return;
                }
                this.props.dispatch({
                  type: 'old_meter_logs/changeSelectRow',
                  payload: [row],
                });
              }
            }

          />
          {
            loading && <Loading/>
          }
        </div>


      </div>
      <div className="table-pagination">
        <MyPagination searchCondition={{ ...searchParams }}
                      resetScrollY={() => {
                        console.log('resetScrollY');
                        const {
                          old_meter_logs: { scrollData },
                        } = this.props;
                        const table = document.querySelector('.react-grid-Canvas');
                        setTimeout(() => {
                          table.scrollTop = 0;
                          table.scrollLeft = scrollData.x;
                        }, 0);

                      }}
                      meta={meta} handleSearch={this.handleSearch}/>
      </div>
      <Drawer
        title={`${this.state.editRecord && this.state.editRecord.name} 详情`}
        placement="right"
        destroyOnClose
        onClose={() => {
          this.setState({
            infoModal: false,
            editRecord: {},
          });
        }}

        width={780}
        visible={this.state.infoModal}
      >
        <Detail meter_number={this.state.editRecord.meter_number}
                id={this.state.editRecord.id}></Detail>
      </Drawer>
    </div>;
  }
}

export default BasicList;
